package org.example.leetcpde;

import org.junit.jupiter.api.Test;

public class simplifyPath {
    @Test
    void simplifyPath() {
        String s = simplifyPath("/a//b////c/d//././/..");
        System.out.println(s);

    }

    public String simplifyPath(String path) {

        class Node {
            String path;
            Node pre;
            Node next;

            public Node(String path) {
                this.path = path;
            }
        }

        String[] split = path.split("\\/");
        Node node = new Node(""), head = node;
        for (String s : split) {
            if (s == null || s.length() == 0) {
                continue;
            } else if (s.equals(".")) {
            } else if (s.equals("..")) {
                node = node.pre;
                if (node == null) {
                    node = head;
                }
                node.next = null;
            } else {
                Node sub = new Node(s);
                sub.pre = node;
                node.next = sub;
                node = sub;
            }

        }

        StringBuilder builder = new StringBuilder();
        Node next = head.next;
        while (next != null) {
            builder.append(next.path).append("/");
            next = next.next;
        }

        if (builder.length() != 0) {
            return "/" +   builder.substring(0, builder.length() -1);
        }

        return "/";
    }
}
